
package biblio.dao;


import biblio.domain.Category;
import biblio.exception.NoSuchEntityException;
import java.io.Serializable;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


/**
 * Default implementation of CategoryDAO.
 *
 * @author mephisto
 */
public class CategoryDAOImpl extends HibernateDaoSupport implements CategoryDAO
{
    /**
     * @throws DataAccessException - in case of Hibernate errors
     */
    public void create(Category category)
    {
        getHibernateTemplate().saveOrUpdate(category);
    }

    /**
     * @throws DataAccessException - in case of Hibernate errors
     */
    public Category find(Serializable categoryName) throws NoSuchEntityException
    {
        List<Category> res = getHibernateTemplate().findByNamedParam("from Category where name = :name", "name", categoryName);
        if (res.isEmpty())
            throw new NoSuchEntityException("No category under name " + categoryName);
        else if(res.size() > 1)
            throw new IllegalStateException("Categories are duplicated but, they have to be unique!");
        return res.get(0);
    }

    /**
     * @throws DataAccessException - in case of Hibernate errors
     */
    public void update(Category category) throws NoSuchEntityException
    {
        getHibernateTemplate().update(category);
    }

    /**
     * @throws DataAccessException - in case of Hibernate errors
     */
    public void delete(Category category)
    {
        getHibernateTemplate().delete(category);
    }

    public List<Category> selectAll()
    {
        return getHibernateTemplate().find("from Category");
    }
}
